package com.jwgf.wifidirect.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.widget.Toast;

import com.jwgf.common.AppContext;
import com.jwgf.wifidirect.callback.DirectActionListener;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;


import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;

import static android.content.Context.WIFI_P2P_SERVICE;
import static android.os.Looper.getMainLooper;


/**
 * 作者：leavesC
 * 时间：2019/2/27 23:58
 * 描述：
 * GitHub：https://github.com/leavesC
 * Blog：https://www.jianshu.com/u/9df45b87cfdf
 */
public class DirectBroadcastReceiver extends BroadcastReceiver {

    public static IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        return intentFilter;
    }

    private static final String TAG = "DirectBroadcastReceiver";

    private WifiP2pManager mWifiP2pManager;

    private WifiP2pManager.Channel mChannel;

    private DirectActionListener mDirectActionListener;

    private HashSet<String> devices = new HashSet<>();

    public DirectBroadcastReceiver() {
        mWifiP2pManager = (WifiP2pManager) AppContext.getInstance().getSystemService(WIFI_P2P_SERVICE);
        mChannel = mWifiP2pManager.initialize(AppContext.getInstance().getBaseContext(), getMainLooper(), null);
        AppContext.getInstance().registerReceiver(this, getIntentFilter());
        Observable.interval(30, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(AppContext.getInstance().getBaseContext(), "success", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int i) {
                        Toast.makeText(AppContext.getInstance().getBaseContext(), "failed", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        });

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action != null) {
            switch (action) {
                // 用于指示 Wifi P2P 是否可用
                case WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION: {
                    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -100);
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
//                        mDirectActionListener.wifiP2pEnabled(true);

                    } else {
//                        mDirectActionListener.wifiP2pEnabled(false);
//                        List<WifiP2pDevice> wifiP2pDeviceList = new ArrayList<>();
//                        mDirectActionListener.onPeersAvailable(wifiP2pDeviceList);
                    }
                    break;
                }
                // 对等节点列表发生了变化
                case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION: {
                    mWifiP2pManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
                        @Override
                        public void onPeersAvailable(WifiP2pDeviceList peers) {

                            for (WifiP2pDevice device : peers.getDeviceList()) {
                                if (!devices.contains(device.deviceName)) {
                                    devices.add(device.deviceName);
                                    if (device.deviceName.contains("MIX")) {
                                        WifiP2pConfig config = new WifiP2pConfig();
                                        config.deviceAddress = device.deviceAddress;
                                        config.wps.setup = WpsInfo.PBC;
//                                        config.groupOwnerIntent = 0;
//                                        mWifiP2pManager.connect(mChannel, config, null);
                                    }
                                }

                            }
//                            mDirectActionListener.onPeersAvailable(peers.getDeviceList());
                        }
                    });
                    break;
                }
                // Wifi P2P 的连接状态发生了改变
                case WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION: {
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo != null && networkInfo.isConnected()) {
                        mWifiP2pManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
                            @Override
                            public void onConnectionInfoAvailable(WifiP2pInfo info) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            ServerSocket serverSocket = new ServerSocket(8888, 10, info.groupOwnerAddress);
                                            serverSocket.setReuseAddress(true);
//                    serverSocket.bind(new InetSocketAddress(8888));
                                            Socket client = serverSocket.accept();
                                            Log.e(TAG, "客户端IP地址 : " + client.getInetAddress().getHostAddress());
                                            InputStream inputStream = client.getInputStream();
                                            byte[] inbuffer = new byte[1024];
                                            int count = inputStream.read(inbuffer);
                                            if (count > 0) {
                                                client.getOutputStream().write("Welcome client".getBytes());
                                            }
                                            serverSocket.close();
                                            inputStream.close();
                                            serverSocket = null;
                                            inputStream = null;
                                        } catch (Exception e) {
                                            Log.e(TAG, "文件接收 Exception: " + e.getMessage());
                                        } finally {

                                        }
                                    }
                                }).start();
//                                mDirectActionListener.onConnectionInfoAvailable(info);


                            }
                        });
                        Log.e(TAG, "已连接p2p设备");
                    } else {
//                        mDirectActionListener.onDisconnection();
                        devices.clear();
                        Log.e(TAG, "与p2p设备已断开连接");
                    }
                    break;
                }
                //本设备的设备信息发生了变化
                case WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION: {
                    WifiP2pDevice wifiP2pDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
//                    mDirectActionListener.onSelfDeviceAvailable(wifiP2pDevice);

                    break;
                }
            }
        }
    }

}